package com.ruoyi.biz.util;

import com.ruoyi.common.utils.LogUtils;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

/**
 * RSA加密工具
 *
 * @author yusheng.liu
 * @since 2025/11/19 10:49
 */
public class MySecurityUtil {

    private final static String PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAu4Cq8Wgn2OtMefnNoqEl" +
            "+AIf2faUWv5ca/NRDxK5rn2vckKmWrA7L0gKyi3QEjWDvCr+zQclmpQlObAl0bYV" +
            "QFWrn7VosxfbMv0z7haKG9xAAeU9HfBfSE/uAc3SIay2CxPlefQET6177Ca4O4Ao" +
            "dyhZopOOgjyoRIM6vrGYAijrxfEEIMenZ80+PK6eM218rpgANU/bDKT8dBpYfC7r" +
            "bmwKQphtsNfzHjXCSNRA5FxvE8cryUMwV5amn6Xr2O1X2V2AAncX+drr3vmXVsR/" +
            "KIum6vb6uLQvneQ3AV/bzgvZThxOsZKMHpEnRjy0ieR3RMaOYj5L+3CLsYtcpSLO" +
            "EQIDAQAB";

    /**
     * 对密码加密
     * @param originPassword 原始密码
     * @return 密文
     * @throws Exception
     */
    public static String encode(String originPassword)  {
       try {
           // LogUtils.getAccessLog().info("[Password]加密-----");
           byte[] keyBytes = Base64.getDecoder().decode(PUBLIC_KEY);
           X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
           PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(spec);

           Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
           cipher.init(Cipher.ENCRYPT_MODE, publicKey);
           byte[] encrypted = cipher.doFinal(originPassword.getBytes(StandardCharsets.UTF_8));

           return Base64.getEncoder().encodeToString(encrypted);
       }catch (Exception e) {
           e.fillInStackTrace();
       }

       return null;
    }
}
